import React from 'react';
import { Card, Form, Input, Select, Button, Space, Table, Modal, message, Tag } from 'antd';
import { useParams, useNavigate, useLocation } from 'react-router-dom';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';

const { Option } = Select;

// 多语言标签示例，模拟与 Vue 字典数据的 label 多语言编辑
const LANGS = [
  { key: 'zh', name: '中文' },
  { key: 'en', name: 'English' },
  { key: 'ja', name: '日本語' },
];

// 模拟数据结构：{ id, codesId, dictType, code, value, labels: { zh: '', en: '', ja: '' }, sort }
function initMock(codesId, dictType) {
  const saved = localStorage.getItem(`dictionary-${codesId}-${dictType}`);
  if (saved) return JSON.parse(saved);
  return Array.from({ length: 8 }).map((_, i) => ({
    id: i + 1,
    codesId,
    dictType,
    code: `${dictType}-${i + 1}`,
    value: `value-${i + 1}`,
    labels: { zh: `示例-${i + 1}`, en: `Sample-${i + 1}`, ja: `サンプル-${i + 1}` },
    sort: i + 1,
    createTime: new Date(Date.now() - i * 86400000).toLocaleString(),
  }));
}

export default function DictionaryData() {
  const { codesId = 'default', dictType = 'default' } = useParams();
  const navigate = useNavigate();
  const location = useLocation();

  const [form] = Form.useForm();
  const [editForm] = Form.useForm();
  const [list, setList] = React.useState(() => initMock(codesId, dictType));
  const [filtered, setFiltered] = React.useState(list);
  const [dialogOpen, setDialogOpen] = React.useState(false);
  const [current, setCurrent] = React.useState(null);

  React.useEffect(() => {
    // 参数变化时，重新初始化数据
    const data = initMock(codesId, dictType);
    setList(data);
    setFiltered(data);
  }, [codesId, dictType]);

  React.useEffect(() => {
    localStorage.setItem(`dictionary-${codesId}-${dictType}`, JSON.stringify(list));
  }, [list, codesId, dictType]);

  const handleSearch = () => {
    const { code, value, label } = form.getFieldsValue();
    const res = list.filter((x) => {
      const m1 = code ? x.code.toLowerCase().includes(code.toLowerCase()) : true;
      const m2 = value ? x.value.toLowerCase().includes(value.toLowerCase()) : true;
      const m3 = label ? Object.values(x.labels).some((lv) => lv.toLowerCase().includes(label.toLowerCase())) : true;
      return m1 && m2 && m3;
    });
    setFiltered(res);
  };

  const onReset = () => {
    form.resetFields();
    setFiltered(list);
  };

  const openDialog = (record) => {
    setCurrent(record || null);
    setDialogOpen(true);
    if (record) {
      editForm.setFieldsValue({ ...record });
    } else {
      editForm.resetFields();
      editForm.setFieldsValue({ codesId, dictType, sort: list.length + 1, labels: { zh: '', en: '', ja: '' } });
    }
  };

  const saveDict = async () => {
    try {
      const values = await editForm.validateFields();
      setList((prev) => {
        if (!current) {
          const id = Date.now();
          return [{ id, createTime: new Date().toLocaleString(), ...values }, ...prev];
        }
        return prev.map((x) => (x.id === current.id ? { ...x, ...values } : x));
      });
      setDialogOpen(false);
      message.success('字典数据已保存（本地模拟）');
    } catch (e) {}
  };

  const delDict = (record) => {
    Modal.confirm({
      title: '删除确认',
      content: `确定删除字典条目 ${record.code} 吗？`,
      onOk: () => {
        setList((prev) => prev.filter((x) => x.id !== record.id));
        message.success('已删除该条目');
      },
    });
  };

  const columns = [
    { title: '编码', dataIndex: 'code', key: 'code', align: 'center' },
    { title: '值', dataIndex: 'value', key: 'value', align: 'center' },
    { title: '中文标签', key: 'labelZh', align: 'center', render: (_, r) => <Tag color="blue">{r.labels?.zh}</Tag> },
    { title: '英文标签', key: 'labelEn', align: 'center', render: (_, r) => <Tag color="green">{r.labels?.en}</Tag> },
    { title: '日文标签', key: 'labelJa', align: 'center', render: (_, r) => <Tag color="orange">{r.labels?.ja}</Tag> },
    { title: '排序', dataIndex: 'sort', key: 'sort', width: 100, align: 'center' },
    { title: '录入时间', dataIndex: 'createTime', key: 'createTime', width: 160, align: 'center' },
    { title: '操作', key: 'actions', width: 160, align: 'center', fixed: 'right', render: (_, record) => (
      <Space size="small">
        <Button size="small" type="primary" icon={<EditOutlined />} onClick={() => openDialog(record)}>编辑</Button>
        <Button size="small" danger icon={<DeleteOutlined />} onClick={() => delDict(record)}>删除</Button>
      </Space>
    ) },
  ];

  return (
    <div className="dictionary-data" style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <Card title={`字典数据（codesId: ${codesId}, dictType: ${dictType})`} variant="outlined">
        <Form form={form} layout="inline" onFinish={handleSearch} style={{ rowGap: 12 }}>
          <Form.Item label="编码" name="code"><Input allowClear placeholder="请输入编码关键词" style={{ width: 220 }} /></Form.Item>
          <Form.Item label="值" name="value"><Input allowClear placeholder="请输入值关键词" style={{ width: 220 }} /></Form.Item>
          <Form.Item label="标签关键词" name="label"><Input allowClear placeholder="多语言标签关键词" style={{ width: 240 }} /></Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">查询</Button>
              <Button onClick={onReset}>重置</Button>
              <Button type="primary" icon={<PlusOutlined />} onClick={() => openDialog(null)}>新增</Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>

      <Card title={`记录（共 ${filtered.length} 条）`} variant="outlined">
        <Table
          rowKey="id"
          dataSource={filtered}
          columns={columns}
          pagination={{ pageSize: 10 }}
          scroll={{ x: 1200 }}
        />
      </Card>

      <Modal open={dialogOpen} title={current ? '编辑字典数据' : '新增字典数据'} okText="保存" cancelText="取消" onOk={saveDict} onCancel={() => setDialogOpen(false)}>
        <Form form={editForm} layout="vertical">
          <Form.Item label="codesId" name="codesId" rules={[{ required: true }]}>
            <Input disabled />
          </Form.Item>
          <Form.Item label="dictType" name="dictType" rules={[{ required: true }]}>
            <Input disabled />
          </Form.Item>
          <Form.Item label="编码(code)" name="code" rules={[{ required: true, message: '请输入编码' }]}>
            <Input />
          </Form.Item>
          <Form.Item label="值(value)" name="value" rules={[{ required: true, message: '请输入值' }]}>
            <Input />
          </Form.Item>

          <Card size="small" title="多语言标签">
            <Form.Item shouldUpdate noStyle>
              {() => {
                const labels = editForm.getFieldValue('labels') || {};
                return (
                  <Space direction="vertical" style={{ width: '100%' }}>
                    <Form.Item label="中文(zh)" name={['labels', 'zh']} rules={[{ required: true, message: '请输入中文标签' }]}>
                      <Input placeholder="例如：状态-启用" />
                    </Form.Item>
                    <Form.Item label="英文(en)" name={['labels', 'en']}>
                      <Input placeholder="e.g., Enabled" />
                    </Form.Item>
                    <Form.Item label="日文(ja)" name={['labels', 'ja']}>
                      <Input placeholder="例：有効" />
                    </Form.Item>
                  </Space>
                );
              }}
            </Form.Item>
          </Card>

          <Form.Item label="排序" name="sort" rules={[{ required: true, message: '请输入排序值' }]}>
            <Input type="number" min={1} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}